const state = {
  pageinfo: {},
  treeId: '',
  treeName: '',
  currentTree: {},
  requestPending: false
}
import router from '@/router/index'

const mutations = {
  SET_PAGEINFO: (state, pageinfo) => {
    state.pageinfo = pageinfo
  },
  SET_TREEID: (state, treeId) => {
    state.treeId = treeId
  },
  SET_TREENAME: (state, treeName) => {
    state.treeName = treeName
  },
  SET_CURRENTTREE: (state, tree) => {
    window.$CD.treeInfo = tree
    window.$CD.treeId = tree[state.treeId] || ''
    state.currentTree = tree
  },
  SET_PENDING: (state, pending) => {
    state.requestPending = pending
  }
}

const actions = {
  setPageInfo({
    commit
  }, pageinfo) {
    console.log(pageinfo)
    let treeId = ''
    let treeName = ''
    try {
      if (pageinfo && pageinfo.treeInfo) {
        const treeInfo = JSON.parse(pageinfo.treeInfo)
        treeId = treeInfo.keyField || ''
        treeName = (treeInfo.displayFields && treeInfo.displayFields.length) ? treeInfo.displayFields[0] : ''
      }
    } catch (e) {}
    commit('SET_TREEID', treeId)
    commit('SET_TREENAME', treeName)
    commit('SET_PAGEINFO', pageinfo)
    commit('SET_CURRENTTREE', {})
  }
}

const getters = {
  clientMacro: (state) => {
    let macro = {}
    // 选中树
    if (state.currentTree && Object.keys(state.currentTree).length && state.treeId) {
      macro['treeKey'] = state.currentTree[state.treeId]
      macro['treeName'] = state.currentTree[state.treeName]
    } else {
      macro['treeKey'] = ''
      macro['treeName'] = ''
    }
    // pageinfo获取参数
    if (state.pageinfo.customParam) {
      try {
        macro = Object.assign(macro, JSON.parse(state.pageinfo.customParam))
      } catch (e) {}
    }
    // 路由参数parentDataId
    if (router.app._route.query && router.app._route.query.parentId) {
      macro['parentDataId'] = router.app._route.query.parentId
    }
    return macro
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
